﻿using System.Collections.Generic;
using System.Linq;

namespace System
{
	internal static class StringExtensions
	{
		public static string EnsureEndsWith(this string value, string end)
		{
			return value.EndsWith(end) ? value : value + end;
		}

		public static string EnsureStartsWith(this string value, string start)
		{
			return value.StartsWith(start) ? value : start + value;
		}

		public static string SafeTrim(this string source)
		{
			return (source == null) ? null : source.Trim();
		}

		public static string SafeTrimEnd(this string source,
		                                 string trimThis,
		                                 StringComparison compareType = StringComparison.OrdinalIgnoreCase)
		{
			if (source == null)
			{
				return null;
			}
			return source.EndsWith(trimThis, compareType) ? source.Substring(0, source.Length - trimThis.Length) : source;
		}

		public static string SafeTrimStart(this string source,
		                                   string trimThis,
		                                   StringComparison compareType = StringComparison.OrdinalIgnoreCase)
		{
			if (source == null)
			{
				return null;
			}
			return source.StartsWith(trimThis, compareType) ? source.Substring(trimThis.Length) : source;
		}

		public static IEnumerable<string> SplitAndTrim(this string source, char seperator, bool removeEmptyElements = true)
		{
			return SplitAndTrim(source, new[] {seperator}, removeEmptyElements);
		}

		public static IEnumerable<string> SplitAndTrim(this string source, char[] seperators, bool removeEmptyElements = true)
		{
			if (source == null)
			{
				return null;
			}
			List<string> split = source.Split(seperators).Select(s => s.Trim()).ToList();
			if (removeEmptyElements)
			{
				split.RemoveAll(s => s == string.Empty);
			}
			return split;
		}
	}

	internal static class EnumerableStringExtensions
	{
		public static bool AnyEndsWith(this IEnumerable<string> items,
		                               string endsWith,
		                               StringComparison comparison = StringComparison.CurrentCulture)
		{
			return items.Any(i => i.EndsWith(endsWith, comparison));
		}

		public static bool AnyStartsWith(this IEnumerable<string> items,
		                                 string beginsWith,
		                                 StringComparison comparison = StringComparison.CurrentCulture)
		{
			return items.Any(i => i.StartsWith(beginsWith, comparison));
		}

		public static IEnumerable<string> ToLowerInvariant(this IEnumerable<string> source)
		{
			return source.Select(item => item.ToLowerInvariant());
		}
	}
}